<template>
  <el-container class="login" direction="vertical">
    <el-main class="login login_main">
      <div class="login_box">
        <el-row>
          <el-col :span="24">
            <h2 class="title">登录</h2>
          </el-col>
        </el-row>
        <el-form
          :model="ruleForm"
          :rules="rules"
          ref="loginForm"
          :status-icon="false"
          class="login_form"
        >
          <el-form-item prop="username">
            <!-- <el-input
              v-model="ruleForm.username"
              placeholder="请输入用户名"
              autocomplete="on"
            ></el-input> -->
            <el-autocomplete
              v-model="ruleForm.username"
              class="account-input"
              placeholder="请输入用户名"
              clearable
              :fetch-suggestions="queryAccount"
              @select="handleSelect"
              @input="enterAccount"
            >
              <template slot-scope="{ item }">
                <div class="account-item">
                  <span>{{ item.account }}</span>
                  <span
                    class="el-icon-circle-close icon-remove"
                    @click="removeAccount(item)"
                  ></span>
                </div>
              </template>
            </el-autocomplete>
          </el-form-item>
          <el-form-item prop="password">
            <el-input
              placeholder="请输入密码"
              v-model="ruleForm.password"
              @keyup.native.enter="submitForm"
              show-password
            ></el-input>
          </el-form-item>
          <el-form-item>
            <el-checkbox v-model="isPwd">记住密码</el-checkbox>
          </el-form-item>
          <el-form-item>
            <el-button
              v-loading="loading"
              element-loading-spinner="el-icon-loading"
              type="primary"
              @click="submitForm"
              class="submit_btn"
              >登录</el-button
            >
          </el-form-item>
        </el-form>
      </div>
    </el-main>
  </el-container>
</template>
<script>
import { login } from "@/api";
// import Router from "vue-router";
import router from "@/router";
import { debounce } from "@/utils/utils";

const logoImage = require("@/assets/logo.png");
const base64 = {
  btoa: str => {
    let t = str;
    // 将密码转成 base64编码
    for (let i = 0; i < 5; i++) {
      t = window.btoa(t);
    }
    return t;
  },
  atob: str => {
    let t = str;
    // 将密码转成 base64编码
    for (let i = 0; i < 5; i++) {
      t = window.atob(t);
    }
    return t;
  }
};
export default {
  name: "page_login",
  componentName: "pageLogin",
  data() {
    const vilidatename = (rule, value, callback) => {
      if (value === "") {
        return callback(new Error("请输入用户名"));
      } else {
        callback();
      }
    };
    const vilidatePass = (rule, value, callback) => {
      if (value === "") {
        return callback(new Error("请输入用户密码"));
      } else {
        callback();
      }
    };
    return {
      logoImage: logoImage,
      ruleForm: {
        username: "",
        password: ""
      },
      rules: {
        username: [{ validator: vilidatename, trigger: "blur" }],
        password: [{ validator: vilidatePass, trigger: "blur" }]
      },
      loading: false,
      isPwd: false, // 记住密码
      accountList: []
    };
  },
  methods: {
    // 返回账号列表
    queryAccount(str, cb) {
      let result = str
        ? this.accountList.filter(this.filterAccount(str))
        : this.accountList;
      cb(result);
    },
    filterAccount(str) {
      return restaurant => {
        return (
          restaurant.account.toLowerCase().indexOf(str.toLowerCase()) === 0
        );
      };
    },
    // 选择账号时
    handleSelect(e) {
      console.info(e);
      this.ruleForm = {
        username: e.account,
        password: e.password
      };
      this.isPwd = e.isPwd;
    },
    enterAccount() {
      if (!this.ruleForm.username) {
        this.ruleForm.password = "";
      }
    },

    submitForm() {
      if (this.loading) return false;
      this.$refs["loginForm"].validate(valid => {
        if (valid) {
          this.login();
          // this.rememberCurrentAccountAndPwd() // 记住保存当前账号密码
        } else {
          return false;
        }
      });
    },

    login: debounce(
      async function() {
        this.loading = true;
        try {
          const res = await login.userLogin({
            username: this.ruleForm.username,
            password: this.ruleForm.password
          });

          this.rememberCurrentAccountAndPwd(); // 记住保存当前账号密码

          for (let k in res.data) {
            if (typeof res.data[k] === "object") {
              localStorage.setItem(k, JSON.stringify(res.data[k]));
            } else {
              localStorage.setItem(k, res.data[k]);
            }
          }

          this.$store.commit("SET_AUTHOR", res.data.authorities);

          // 登录成功之后，获取菜单列表
          this.getMenuList(res.data.userId);
        } catch {
          this.loading = false;
        }
      },
      1000,
      true
    ),

    // 获取菜单列表
    async getMenuList(id) {
      const res = await login.treeByUser(id);
      console.log(res.data);
      localStorage.setItem("routes", JSON.stringify(res.data));

      if (res.data.length === 0) {
        localStorage.removeItem("token");
        this.$message.error("你没有可访问的页面权限，请更换账号重新登录");
        this.loading = false;
        // this.$router.push('/login')
      } else {
        // 调用添加动态路由方法，将当前用户的菜单传过去处理
        this.$getRoutes(res.data, routes => {
          router.addRoutes(routes);

          this.$store.dispatch("ws", id);
          this.loading = false;

          let rs = [];
          res.data.forEach(r => {
            rs.push(...r.children);
          });
          // 在菜单中查找与预跳转匹配的路径
          const findPath = rs.find(r => r.path === this.$route.query.pathFrom);
          const path = findPath ? `/admin${findPath.path}` : "/admin/";
          window.open(path, "_self");
        });
      }
    },

    // 记住当前账号密码，存到localStorage
    rememberCurrentAccountAndPwd() {
      const index = this.accountList.findIndex(
        a => a.account === this.ruleForm.username
      );
      const data = {
        account: this.ruleForm.username,
        password: this.isPwd ? this.ruleForm.password : "",
        isPwd: this.isPwd
      };
      // 如果账号不存在，则push新增，存在则重新赋值
      index === -1
        ? this.accountList.push(data)
        : this.accountList.splice(index, 1, data);

      let list = this.accountList.map(a => ({ ...a }));
      list.forEach(a => {
        a.password = base64.btoa(a.password);
      });

      window.localStorage.setItem("AccountList", JSON.stringify(list));
    },

    // 获取账号列表
    getAccountList() {
      const accountList = JSON.parse(
        window.localStorage.getItem("AccountList")
      );
      if (accountList && accountList.length !== 0) {
        accountList.forEach(a => {
          if (a.password) {
            a.password = base64.atob(a.password);
          }
        });
        this.accountList = accountList;
        // 把第一个账号填充到表单上
        this.ruleForm = {
          username: accountList[0].account,
          password: accountList[0].password
        };
        this.isPwd = accountList[0].isPwd;
      } else {
        this.accountList = [];
      }
    },

    // 移除一个账号
    removeAccount(data) {
      const index = this.accountList.findIndex(a => a.account === data.account);
      this.accountList.splice(index, 1);
      this.ruleForm.username = "";
      let list = this.accountList.map(a => ({ ...a }));
      list.forEach(a => {
        a.password = base64.btoa(a.password);
      });
      window.localStorage.setItem("AccountList", JSON.stringify(list));
      console.log(this.accountList);
    }
  },

  created() {
    this.getAccountList();
  }
};
</script>

<style scoped lang="scss">
.login {
  height: 100%;

  /deep/ &.login_main {
    position: relative;
    .login_box {
      max-width: 400px;
      padding: 40px;
      margin: 10% auto;
      border-radius: 20px;
      box-shadow: 0 0 28px 4px #d5d5d5;
      .logo {
        width: 48px;
        height: 48px;
      }
      .title {
        line-height: 48px;
        font-size: 38px;
        font-weight: bolder;
        text-align: center;
        text-transform: capitalize;
        letter-spacing: 5px;
        color: #344b5e;
        text-shadow: 1px 1px 3px rgba(0, 0, 0, 0.2);
      }
      .welcome {
        color: #13161b;
        font-family: "Neue Haas Unica Pro", sans-serif;
        font-weight: 400;
        line-height: 2.4;
        font-size: 28px;
      }
      .login_form {
        margin-top: 50px;
        .submit_btn {
          width: 100%;
        }
      }
    }
  }

  & /deep/ .el-loading-spinner {
    top: 86%;
  }

  .account-input {
    width: 100%;
  }
}

// 账号
.account-item {
  display: flex;
  align-items: center;
  justify-content: space-between;

  .icon-remove {
    font-size: 18px;
    color: #c1c1c1;
    &:hover {
      opacity: 0.8;
    }
  }
}
</style>
